package com.js.nickcar.base;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by LZY on 2017/9/28.
 */

public class BasePresenter<V extends BaseView> {

    public V mView;
    public CompositeSubscription mCompositeSubscription;

    public void attachView(V mvpView) {
        this.mView = mvpView;
    }

    public void detachView() {
        this.mView = null;
        onUnsubscribe();
    }

    public <T> void addSubscription(Observable<T> observable, Subscriber<T> subscriber) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber));
    }

    /**
     * RXjava取消注册，以避免内存泄露
     */
    public void onUnsubscribe() {
        if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.unsubscribe();
        }
    }

    public void showToast(String msg) {
        mView.showToast(msg);
    }


}
